/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import com.sun.lwuit.ComboBox;
import com.sun.lwuit.Form;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.Command;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.SelectionListener;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMException;

/**
 *
 * @author Kvest
 */
public class PhoneForm extends Form implements ActionListener
{
    public static final int CALL_ID = 1;
    public static final int BACK_ID = 2;

    private FormAction listener;
    private Command call;
    private Command back;

    private TextField phoneNumber;
    private ComboBox phoneList;

    public PhoneForm(FormAction listener)
    {
        super("Звонок");
        this.listener = listener;
        
        init();
    }

    private void init()
    {
        addCommandListener(this);

        back= new Command("Назад", BACK_ID);
        addCommand(back);

        call = new Command("Звонить",CALL_ID);
        addCommand(call);

        //Поле ввода номера телефона
        addComponent(new Label("Номер:"));
        phoneNumber = new TextField();
        phoneNumber.setSelectCommandText("");
        phoneNumber.setInputModeOrder(new String[]{"123"});
        phoneNumber.setConstraint(TextArea.PHONENUMBER);
        addComponent(phoneNumber);

        //Список телефонов
        addComponent(new Label("Номера:"));
	phoneList = new ComboBox(new String[]{"Идет загрузка..."});
        phoneList.setSelectCommandText("");
        phoneList.addSelectionListener(new SelectionListener()
        {
            public void selectionChanged(int oldSelected, int newSelected)
            {
                String selectedText = (String)phoneList.getSelectedItem();
                //Если строку можно разделить на имя и номер
                if (selectedText != null && selectedText.indexOf(":") != -1)
                {
                    selectedText = selectedText.substring(selectedText.lastIndexOf(':') + 1);
                    phoneNumber.setText(selectedText);
                }
            }
        });
        addComponent(phoneList);

        //В отдельном потоке начинаем грузить номера телефонов
        (new Thread(new Runnable()
        {
            public void run()
            {
                getPhones();
            }
        })).start();
    }

    public void actionPerformed(ActionEvent evt)
    {
        if (listener != null)
        {
            listener.commandAction(evt.getCommand().getId());
        }
    }

    public String getPhoneNumber()
    {
        return phoneNumber.getText();
    }

    public void getPhones()
    {
        //Получаем контакты
        Vector phones = getContacts();

        if (phones.size() == 0)
        {
            return;
        }

        //Удаляем все элементы, которые там были до этого
        while (phoneList.getModel().getSize() > 0)
        {
            phoneList.getModel().removeItem(0);
        }

        //Добавляем остальные номера
        Pair tmp;
        for (int i = 0; i < phones.size(); ++i)
        {
            tmp = (Pair)phones.elementAt(i);
            if ((tmp.getPhone() != null) && (!tmp.getPhone().equals("")))
            {
                phoneList.addItem(tmp.getName() + ":" + tmp.getPhone());
            }
        }
    }

    private class Pair
    {
        private String name;
        private String phone;

        public Pair(String name, String phone)
        {
            this.name = name;
            this.phone = phone;
        }

        public String getName()
        {
            return name;
        }

        public String getPhone()
        {
            return phone;
        }
    }

    private Vector getContacts()
    {
        Vector result = new Vector();

        String[] lists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);

        for (int i = 0; i < lists.length; ++i)
        {
            PIM pim = PIM.getInstance();
            ContactList clist;
            try
            {
                clist = (ContactList) pim.openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, lists[i]);
            }
            catch(Exception e)
            {
                continue;
            }

            Enumeration contacts;
            try
            {
                contacts = clist.items();
            }
            catch (PIMException e)
            {
                continue;
            }

            String name,phone;
            while (contacts.hasMoreElements())
            {
                try
                {
                    Contact c = (Contact) contacts.nextElement();

                    //Имя
                    if (c.countValues(Contact.FORMATTED_NAME) > 0)
                    {
                        name = c.getString(Contact.FORMATTED_NAME, 0);
                    }
                    else
                    {
                        name = "";
                    }

                    //Номер телефона
                    if (c.countValues(Contact.TEL) > 0)
                    {
                        phone = c.getString(Contact.TEL, 0);
                    }
                    else
                    {
                        phone = "";
                    }

                    result.addElement(new Pair(name, phone));

                } catch(Exception e){}
            }
        }

        return result;
    }
}
